<template>
  <el-dialog
    title="发送学员通知"
    :visible.sync="visible"
    width="50%"
    :before-close="handleClose"
  >
    <el-form :model="noticeForm" ref="noticeForm" :rules="noticeRules">
      <el-form-item label="通知类型" prop="sendTypes">
        <el-checkbox-group v-model="noticeForm.sendTypes">
          <el-checkbox label="0">短信</el-checkbox>
          <el-checkbox label="1">门户</el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <el-form-item label="通知内容" prop="content">
        <el-input
          type="textarea"
          v-model="noticeForm.content"
          placeholder="请输入通知内容"
          rows="6"
          maxlength="500"
          show-word-limit
        ></el-input>
      </el-form-item>

      <el-form-item label="发送范围">
        <el-radio-group v-model="noticeForm.range" @change="handleRangeChange">
          <el-radio label="all">所有学员</el-radio>
          <el-radio label="selected">指定学员</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item
        v-if="noticeForm.range === 'selected'"
        class="selected-users-form-item"
        prop="selectedUsers"
        :rules="[{ required: true, message: '请至少选择一个学员', trigger: 'change' }]"
      >
        <el-select
          v-model="noticeForm.selectedUsers"
          multiple
          placeholder="请输入学员姓名搜索并选择"
          filterable
          remote
          :remote-method="queryUsers"
          :loading="userLoading"
          style="width: 100%;"
          clearable
          @clear="handleSelectClear"
        >
          <el-option
            v-for="user in userOptions"
            :key="user.id"
            :label="user.name"
            :value="user.id"
          >
            <span style="float: left">{{ user.name }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">
              身份证号：{{ user.idCard || '无证件号' }}
            </span>
          </el-option>
          <template #empty>
            <div style="text-align: center; color: #909399;">
              {{ userLoading ? '搜索中...' : '无匹配学员，请更换关键词' }}
            </div>
          </template>
        </el-select>
        <div class="selected-count" v-if="noticeForm.range === 'selected'">
          已选择 {{ noticeForm.selectedUsers.length }} 名学员
        </div>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="submitNotice" :loading="noticeLoading">发送</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getExamListByClassId } from "@/api/examination/examRecord";
import { studentNoticeProcess } from "@/api/training/studentNotice.js";

export default {
  name: "StudentNoticeDialog",
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    classId: {
      type: [String, Number],
      required: true
    }
  },
  data() {
    return {
      noticeForm: {
        title: '',
        content: '',
        range: 'all',
        selectedUsers: [],
        sendTypes: []
      },
      noticeLoading: false,
      noticeRules: {
        sendTypes: [{ required: true, message: '请选择通知类型', trigger: 'change' }],
        content: [{ required: true, message: "请输入通知内容", trigger: "blur" }, { max: 500, message: '内容不能超过500个字符', trigger: 'blur' }],
      },
      userLoading: false,
      userOptions: [],
      allUsers: []
    };
  },
  watch: {
    visible(newVal) {
      if (newVal) {
        this.initNoticeForm();
        this.loadAllUsers();
      }
    },
    classId(newVal) {
      if (newVal) {
        this.loadAllUsers();
      }
    }
  },
  methods: {
    initNoticeForm() {
      this.noticeForm = {
        title: '',
        content: '',
        range: 'all',
        selectedUsers: [],
        sendTypes: []
      };
      this.$nextTick(() => {
        if (this.$refs.noticeForm) this.$refs.noticeForm.clearValidate();
      });
    },
    async loadAllUsers() {
      try {
        const res = await getExamListByClassId({
          trainingClassId: this.classId,
          pageNum: 1,
          pageSize: 1000
        });

        if (res.code === 200 && Array.isArray(res.rows)) {
          this.allUsers = res.rows.map(item => ({
            id: item.studentId || "-",
            name: item.studentName || "-",
            idCard: item.idNumber || "-"
          }));
          this.userOptions = [...this.allUsers];
          this.noticeForm.selectedUsers = this.allUsers.map(user => user.id);
        }
      } catch (error) {
        this.$message.error("加载学员列表失败");
        console.error("加载学员列表错误:", error);
      }
    },
    handleRangeChange(newRange) {
      if (newRange === 'all') {
        this.noticeForm.selectedUsers = this.allUsers.map(user => user.id);
      } else {
        this.noticeForm.selectedUsers = [];
      }
      this.$nextTick(() => {
        if (this.$refs.noticeForm) this.$refs.noticeForm.clearValidate('selectedUsers');
      });
    },
    handleSelectClear() {
      this.noticeForm.selectedUsers = [];
    },
    queryUsers(query) {
      if (!query) {
        this.userOptions = [...this.allUsers];
        return;
      }
      this.userLoading = true;
      setTimeout(() => {
        this.userOptions = this.allUsers.filter(user =>
          user.name.includes(query) || user.idCard.includes(query)
        );
        this.userLoading = false;
      }, 300);
    },
    async submitNotice() {
      this.$refs.noticeForm.validate(async valid => {
        if (valid) {
          this.noticeLoading = true;
          try {
            const params = {
              sendType: this.noticeForm.range === 'all' ? "1" : "2",
              studentIds: this.noticeForm.range === 'all' ? [] : this.noticeForm.selectedUsers,
              isSms: this.noticeForm.sendTypes.includes('0') ? "1" : "0",
              isPortal: this.noticeForm.sendTypes.includes('1') ? "1" : "0",
              noticeTitle: this.noticeForm.title,
              noticeContent: this.noticeForm.content,
              sendTime: new Date().toLocaleString('zh-CN', {
                year: 'numeric', month: '2-digit', day: '2-digit',
                hour: '2-digit', minute: '2-digit', second: '2-digit',
                hour12: false
              }).replace(/\//g, '-'),
              trainingClassId: this.classId
            };
            const res = await studentNoticeProcess(params);
            if (res.code === 200) {
              this.$message.success('通知发送成功');
              this.$emit('notice-sent');
              this.visible = false;
            } else {
              this.$message.error(res.msg || '通知发送失败');
            }
          } catch (err) {
            this.$message.error('通知发送失败：' + (err.msg || err.message));
          } finally {
            this.noticeLoading = false;
          }
        }
      });
    },
    handleClose() {
      this.$emit('notice-sent');
    }
  }
};
</script>

<style scoped>
.selected-users-form-item {
  margin-top: 10px;
}
.selected-count {
  margin-top: 5px;
  font-size: 12px;
  color: #666;
}
</style>
